package grp.test.service.Impl;

import grp.test.common.ResponseCode;
import grp.test.common.ServerResponse;
import grp.test.dao.BookMapper;
import grp.test.dao.FavoriteMapper;
import grp.test.pojo.Book;
import grp.test.pojo.Favorite;
import grp.test.pojo.FavoriteKey;
import grp.test.service.IFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("iFavoriteService")
public class IFavoriteServiceImpl implements IFavoriteService {
    @Autowired(required=false)
    FavoriteMapper favoriteMapper;
    @Autowired(required=false)
    BookMapper bookMapper;
    @Override
    public ServerResponse<String> addFavoriteBook(Integer userId, Integer bookId) {
        Date date = new Date();
        Favorite favorite = new Favorite(bookId,userId,date);
        int response = favoriteMapper.insert(favorite);
        if(response == 0)
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(), "添加收藏失败");
        return ServerResponse.createBySuccessMessage("添加收藏成功");
    }

    @Override
    public ServerResponse<List<Book>> getbookList(Integer userId) {
        List<Favorite> favoriteList = favoriteMapper.selectAllBy(userId);
        if (favoriteList == null)
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),"你还没有收藏书籍");
        List<Book> bookList = new ArrayList<>();
        for (int i=0;i<favoriteList.size();i++){
            bookList.add(bookMapper.selectByPrimaryKey(favoriteList.get(i).getBookId()));
        }
        return ServerResponse.createBySuccess("数据读取成功",bookList);
    }

    @Override
    public ServerResponse<String> removeFavoriteBook(Integer userId, Integer bookId) {
        int response = favoriteMapper.deleteByPrimaryKey(new FavoriteKey(bookId,userId));
        if (response == 0)
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR.getCode(),
                    "取消收藏失败，请重试");
        return ServerResponse.createBySuccessMessage("取消收藏成功");
    }

    @Override
    public ServerResponse<Favorite> selectSingleFavorite(Integer userId, Integer bookId) {
        Favorite favorite = favoriteMapper.selectByUserAndBookKey(userId, bookId);
        System.out.println(favorite);
        return ServerResponse.createBySuccess(favorite);
    }
}
